<template>
  <div class="campus-payment">
    <!-- 学生专用：学费/住宿费缴费区域 -->
    <el-row v-if="userRole === 'STUDENT'" :gutter="24" style="margin-bottom: 24px;">
      <el-col :span="24">
        <el-card>
          <div class="section-title">学费/住宿费缴费</div>
          <el-alert
            v-if="!isStudentValid"
            title="专业信息不完整"
            type="warning"
            description="您的专业信息不完整，请联系管理员完善信息后再进行缴费。"
            show-icon
            style="margin-bottom: 16px;"
          />
          <el-form :inline="true" label-width="80px" v-else>
            <el-form-item label="缴费类型">
              <el-select v-model="selectedFeeType" placeholder="请选择缴费类型" style="width: 160px" @change="onFeeTypeChange">
                <el-option label="学费" value="tuition" />
                <el-option label="住宿费" value="accommodation" />
              </el-select>
            </el-form-item>
            <el-form-item label="金额">
              <el-input v-model="feeAmount" :disabled="true" style="width: 120px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="!selectedFeeType || hasPaid[selectedFeeType]" @click="handlePayFee">
                {{ hasPaid[selectedFeeType] ? '已缴费' : '缴费' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 校园卡充值区域 -->
    <el-row :gutter="24" style="margin-bottom: 24px;">
      <el-col :span="12">
        <el-card>
          <div class="section-title">校园卡充值</div>
          <div style="margin-bottom: 12px;">当前余额：<span style="color: #409eff; font-weight: bold;">￥{{ cardBalance.toFixed(2) }}</span></div>
          <el-radio-group v-model="rechargeAmount" size="large">
            <el-radio-button :label="50">50元</el-radio-button>
            <el-radio-button :label="100">100元</el-radio-button>
            <el-radio-button :label="150">150元</el-radio-button>
            <el-radio-button :label="200">200元</el-radio-button>
          </el-radio-group>
          <el-button type="primary" style="margin-left: 16px;" :disabled="!rechargeAmount" @click="handleRecharge">充值</el-button>
        </el-card>
      </el-col>
      
      <!-- 管理员专用：查询统计 -->
      <el-col v-if="userRole === 'ADMIN'" :span="12">
        <el-card>
          <div class="section-title">缴费统计</div>
          <div style="margin-bottom: 12px;">
            <el-statistic title="总订单数" :value="totalOrders" />
          </div>
          <div style="margin-bottom: 12px;">
            <el-statistic title="已支付订单" :value="paidOrders" />
          </div>
          <div>
            <el-statistic title="总金额" :value="totalAmount" prefix="￥" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 历史缴费记录 -->
    <el-card class="history-section">
      <div class="section-title">
        历史缴费记录
        <span v-if="userRole === 'ADMIN'" style="font-size: 14px; color: #666; margin-left: 16px;">（管理员可查看所有记录）</span>
      </div>
      
      <!-- 管理员专用：高级查询 -->
      <el-form v-if="userRole === 'ADMIN'" :inline="true" style="margin-bottom: 16px;">
        <el-form-item label="用户名">
          <el-input v-model="searchUsername" placeholder="输入用户名" style="width: 140px" />
        </el-form-item>
        <el-form-item label="缴费类型">
          <el-select v-model="searchCategory" placeholder="全部类型" style="width: 140px">
            <el-option label="全部" value="" />
            <el-option label="学费" value="tuition" />
            <el-option label="住宿费" value="accommodation" />
            <el-option label="校园卡充值" value="card_recharge" />
          </el-select>
        </el-form-item>
        <el-form-item label="学年">
          <el-select v-model="selectedYear" placeholder="全部学年" style="width: 140px">
            <el-option label="全部" value="" />
            <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchHistory">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 普通用户：简单查询 -->
      <el-form v-else :inline="true" style="margin-bottom: 16px;">
        <el-form-item label="学年">
          <el-select v-model="selectedYear" placeholder="全部学年" style="width: 140px" @change="fetchHistory">
            <el-option label="全部" value="" />
            <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费类型">
          <el-select v-model="searchCategory" placeholder="全部类型" style="width: 140px" @change="fetchHistory">
            <el-option label="全部" value="" />
            <el-option label="学费" value="tuition" />
            <el-option label="住宿费" value="accommodation" />
            <el-option label="校园卡充值" value="card_recharge" />
          </el-select>
        </el-form-item>
      </el-form>

      <el-table :data="historyList" style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="category" label="缴费类型" width="120">
          <template #default="scope">
            {{ getCategoryLabel(scope.row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
            ￥{{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payMethod" label="支付方式" width="120">
          <template #default="scope">
            {{ getPayMethodLabel(scope.row.payMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="支付时间" width="180">
          <template #default="scope">
            {{ scope.row.payTime ? formatDate(scope.row.payTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column v-if="userRole === 'ADMIN'" prop="userId" label="用户ID" width="100" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 支付弹窗 -->
    <el-dialog v-model="showPayDialog" title="支付订单" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="text-align: center;">
        <div style="margin-bottom: 20px;">
          <h3>{{ getCategoryLabel(payCategory) }}</h3>
          <p style="font-size: 24px; color: #409eff; font-weight: bold;">￥{{ payAmount }}</p>
        </div>
        
        <div style="margin-bottom: 20px;">请选择支付方式：</div>
        <el-radio-group v-model="payMethod" size="large">
          <el-radio-button label="alipay">支付宝</el-radio-button>
          <el-radio-button label="wechat">微信支付</el-radio-button>
        </el-radio-group>
        
        <div v-if="payMethod" style="margin: 20px 0;">
          <div>请使用{{ getPayMethodLabel(payMethod) }}扫码支付</div>
          <canvas ref="qrcodeCanvas" style="margin: 10px auto; display: block; border: 1px solid #ddd;"></canvas>
          <div v-if="payMethod === 'alipay'" style="margin-top: 10px; color: #409eff; font-size: 14px;">
            请使用支付宝沙箱扫码支付，支付成功后会自动确认
          </div>
          <el-button v-else type="primary" style="margin-top: 10px;" @click="handleSimulateScan" :disabled="scanned">模拟扫码</el-button>
          <div v-if="scanned" style="color: #67c23a; margin-top: 8px;">扫码成功！</div>
        </div>
        
        <div style="margin: 15px 0; color: #f56c6c; font-size: 16px;">
          剩余支付时间：{{ countdownText }}
        </div>
        
        <div style="margin-top: 20px;">
          <el-button type="success" size="large" @click="handlePaySuccess">支付完成</el-button>
          <el-button size="large" style="margin-left: 12px;" @click="handleCancelOrder">取消订单</el-button>
          <el-button size="large" style="margin-left: 12px;" @click="handleBackToPayment">返回缴费</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="showOrderDetail" title="订单详情" width="600px">
      <div v-if="selectedOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="缴费类型">{{ getCategoryLabel(selectedOrder.category) }}</el-descriptions-item>
          <el-descriptions-item label="金额">￥{{ selectedOrder.amount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusLabel(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ getPayMethodLabel(selectedOrder.payMethod) }}</el-descriptions-item>
          <el-descriptions-item label="学年">{{ selectedOrder.year || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedOrder.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ selectedOrder.payTime ? formatDate(selectedOrder.payTime) : '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 管理员显示学校账户余额 -->
    <el-card v-if="userRole === 'ADMIN'" style="margin-top: 24px;">
      <div class="section-title">学校账户余额：<span style="color: #409eff; font-weight: bold;">￥{{ schoolAccount.balance }}</span></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  createOrder, payOrder, cancelOrder, getUserOrders, getAllOrders, 
  getCardBalance, getStudentFees, validateStudentMajor 
} from '@/api/payment'
import QRCode from 'qrcode'

// 用户信息
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const userId = userInfo.id
const userRole = userInfo.role

// 学生专业验证
const isStudentValid = ref(true)

// 学生专业费用
const studentFees = ref({})
const selectedFeeType = ref('')
const feeAmount = ref('')
const hasPaid = reactive({ tuition: false, accommodation: false })

// 校园卡充值
const cardBalance = ref(0)
const rechargeAmount = ref(null)

// 历史记录
const historyList = ref([])
const yearOptions = ref([])
const selectedYear = ref('')
const searchCategory = ref('')
const searchUsername = ref('')
const loading = ref(false)

// 管理员统计
const totalOrders = computed(() => historyList.value.length)
const paidOrders = computed(() => historyList.value.filter(item => item.status === 'paid').length)
const totalAmount = computed(() => {
  return historyList.value
    .filter(item => item.status === 'paid')
    .reduce((sum, item) => sum + Number(item.amount), 0)
    .toFixed(2)
})

// 支付弹窗
const showPayDialog = ref(false)
const payMethod = ref('alipay')
const payOrderNo = ref('')
const payCategory = ref('')
const payAmount = ref(0)
const countdown = ref(1200) // 20分钟
const countdownText = ref('20:00')
let countdownTimer = null
let paymentStatusTimer = null
const scanned = ref(false)
const schoolAccount = ref({ balance: 0 })

// 订单详情弹窗
const showOrderDetail = ref(false)
const selectedOrder = ref(null)

// 订单支付二维码
const qrcodeCanvas = ref(null)

// 工具函数
function formatDate(dateStr) {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

function getCategoryLabel(cat) {
  return cat === 'tuition' ? '学费' : cat === 'accommodation' ? '住宿费' : cat === 'card_recharge' ? '校园卡充值' : cat
}

function getPayMethodLabel(method) {
  return method === 'alipay' ? '支付宝' : method === 'wechat' ? '微信支付' : '-'
}

function getStatusLabel(status) {
  return status === 'paid' ? '已支付' : status === 'pending' ? '待支付' : status === 'cancelled' ? '已取消' : '已过期'
}

function getStatusType(status) {
  return status === 'paid' ? 'success' : status === 'pending' ? 'warning' : 'danger'
}

// 选择缴费类型时自动显示金额
function onFeeTypeChange() {
  if (selectedFeeType.value && studentFees.value[selectedFeeType.value]) {
    feeAmount.value = studentFees.value[selectedFeeType.value]
  } else {
    feeAmount.value = ''
  }
}

// 查询校园卡余额
async function fetchCardBalance() {
  try {
    const res = await getCardBalance(userId)
    cardBalance.value = res.balance || 0
  } catch (error) {
    console.error('获取余额失败:', error)
  }
}

// 获取学生专业费用
async function fetchStudentFees() {
  if (userRole !== 'STUDENT') return
  
  try {
    const res = await getStudentFees(userId)
    studentFees.value = res
  } catch (error) {
    console.error('获取专业费用失败:', error)
  }
}

// 验证学生专业信息
async function validateStudent() {
  if (userRole !== 'STUDENT') return
  
  try {
    const res = await validateStudentMajor(userId)
    isStudentValid.value = res.valid
  } catch (error) {
    console.error('验证学生信息失败:', error)
    isStudentValid.value = false
  }
}

// 获取学校账户余额（管理员）
async function fetchSchoolAccount() {
  if (userRole === 'ADMIN') {
    try {
      const res = await fetch('/api/payment/school/account').then(r => r.json())
      schoolAccount.value = res
    } catch (e) {
      schoolAccount.value = { balance: 0 }
    }
  }
}

// 查询历史缴费记录
async function fetchHistory() {
  loading.value = true
  try {
    let res
    if (userRole === 'ADMIN') {
      res = await getAllOrders(selectedYear.value, searchCategory.value, searchUsername.value)
    } else {
      res = await getUserOrders(userId, selectedYear.value, searchCategory.value, userRole)
    }
    
    historyList.value = res || []
    
    // 统计已缴费类型（仅学生）
    if (userRole === 'STUDENT') {
      hasPaid.tuition = historyList.value.some(item => item.category === 'tuition' && item.status === 'paid')
      hasPaid.accommodation = historyList.value.some(item => item.category === 'accommodation' && item.status === 'paid')
    }
    
    // 学年选项
    const years = new Set()
    historyList.value.forEach(item => { if (item.year) years.add(item.year) })
    yearOptions.value = Array.from(years).sort().reverse()
  } catch (error) {
    console.error('获取历史记录失败:', error)
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索条件
function resetSearch() {
  searchUsername.value = ''
  searchCategory.value = ''
  selectedYear.value = ''
  fetchHistory()
}

// 缴费按钮
async function handlePayFee() {
  if (!selectedFeeType.value) return
  
  // 验证学生专业信息
  if (!isStudentValid.value) {
    ElMessage.error('专业信息不完整，无法创建缴费订单')
    return
  }
  
  // 创建订单
  const orderData = {
    userId,
    category: selectedFeeType.value,
    amount: studentFees.value[selectedFeeType.value],
    status: 'pending',
    year: new Date().getFullYear() + '-' + (new Date().getFullYear() + 1)
  }
  
  try {
    const res = await createOrder(orderData)
    if (res) {
      payOrderNo.value = res.orderNo
      payCategory.value = res.category
      payAmount.value = res.amount
      showPayDialog.value = true
      startCountdown()
      await nextTick()
      generateQRCode()
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败')
  }
}

// 校园卡充值按钮
async function handleRecharge() {
  if (!rechargeAmount.value) return
  
  // 创建充值订单
  const orderData = {
    userId,
    category: 'card_recharge',
    amount: rechargeAmount.value,
    status: 'pending',
    year: new Date().getFullYear() + '-' + (new Date().getFullYear() + 1)
  }
  
  try {
    const res = await createOrder(orderData)
    if (res) {
      payOrderNo.value = res.orderNo
      payCategory.value = res.category
      payAmount.value = res.amount
      showPayDialog.value = true
      startCountdown()
      await nextTick()
      generateQRCode()
    }
  } catch (error) {
    console.error('创建充值订单失败:', error)
    ElMessage.error('创建充值订单失败')
  }
}

// 支付弹窗相关
function startCountdown() {
  countdown.value = 1200
  updateCountdownText()
  scanned.value = false
  if (countdownTimer) clearInterval(countdownTimer)
  countdownTimer = setInterval(() => {
    countdown.value--
    updateCountdownText()
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      handleCancelOrder()
      ElMessage.warning('订单已超时自动取消')
    }
  }, 1000)
}

function updateCountdownText() {
  const min = Math.floor(countdown.value / 60)
  const sec = countdown.value % 60
  countdownText.value = `${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')}`
}

async function generateQRCode() {
  if (!payOrderNo.value || !payMethod.value) return
  
  if (payMethod.value === 'alipay') {
    // 调用支付宝接口获取真实二维码
    try {
      const res = await payOrder(payOrderNo.value, payMethod.value)
      if (res.success && res.qrCode) {
        QRCode.toCanvas(qrcodeCanvas.value, res.qrCode, { width: 180 }, err => {
          if (err) console.error('二维码生成失败', err)
        })
        scanned.value = false
        // 开始轮询支付状态
        startPaymentStatusPolling()
      } else {
        ElMessage.error(res.message || '获取支付二维码失败')
      }
    } catch (error) {
      console.error('获取支付宝二维码失败:', error)
      ElMessage.error('获取支付二维码失败')
    }
  } else {
    // 微信支付或其他支付方式的模拟二维码
    const qrContent = `模拟支付|订单号:${payOrderNo.value}|方式:${getPayMethodLabel(payMethod.value)}`
    QRCode.toCanvas(qrcodeCanvas.value, qrContent, { width: 180 }, err => {
      if (err) console.error('二维码生成失败', err)
    })
    scanned.value = false
  }
}

// 支付完成
async function handlePaySuccess() {
  if (payMethod.value === 'alipay') {
    // 支付宝支付通过轮询自动处理，这里主要用于其他支付方式
    ElMessage.info('支付宝支付请等待自动确认')
    return
  }
  
  if (!scanned.value) {
    ElMessage.error('请先扫码支付')
    return
  }
  try {
    const res = await payOrder(payOrderNo.value, payMethod.value)
    if (res.success) {
      ElMessage.success('支付成功')
      showPayDialog.value = false
      fetchHistory()
      if (payCategory.value === 'card_recharge') fetchCardBalance()
      if (userRole === 'ADMIN') fetchSchoolAccount()
    } else {
      ElMessage.error('支付失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  }
}

// 取消订单
async function handleCancelOrder() {
  try {
    await cancelOrder(payOrderNo.value)
    showPayDialog.value = false
    stopPaymentStatusPolling()
    fetchHistory()
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  }
}

// 返回缴费页面
function handleBackToPayment() {
  showPayDialog.value = false
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
  stopPaymentStatusPolling()
}

// 查看订单详情
function viewOrderDetail(order) {
  selectedOrder.value = order
  showOrderDetail.value = true
}

// 监听支付方式变化
watch(payMethod, () => {
  nextTick(() => generateQRCode())
})

// 开始轮询支付状态
function startPaymentStatusPolling() {
  if (paymentStatusTimer) clearInterval(paymentStatusTimer)
  paymentStatusTimer = setInterval(async () => {
    try {
      // 先查询本地订单状态
      const localRes = await fetch(`/api/payment/alipay/status?orderNo=${payOrderNo.value}`).then(r => r.json())
      if (localRes.success && localRes.status === 'paid') {
        clearInterval(paymentStatusTimer)
        scanned.value = true
        ElMessage.success('支付成功！')
        // 自动关闭弹窗并刷新数据
        setTimeout(() => {
          showPayDialog.value = false
          fetchHistory()
          if (payCategory.value === 'card_recharge') fetchCardBalance()
          if (userRole === 'ADMIN') fetchSchoolAccount()
        }, 1500)
        return
      }
      
      // 如果本地状态未更新，查询支付宝订单状态
      const alipayRes = await fetch(`/alipay/query?outTradeNo=${payOrderNo.value}`).then(r => r.json())
      if (alipayRes.success && alipayRes.tradeStatus === 'TRADE_SUCCESS') {
        // 支付宝显示支付成功，但本地可能还未更新，等待回调处理
        console.log('支付宝订单已支付成功，等待回调处理...')
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
    }
  }, 3000) // 每3秒查询一次
}

// 停止轮询支付状态
function stopPaymentStatusPolling() {
  if (paymentStatusTimer) {
    clearInterval(paymentStatusTimer)
    paymentStatusTimer = null
  }
}

// 模拟扫码
function handleSimulateScan() {
  scanned.value = true
  ElMessage.success('扫码成功，请点击支付完成')
}

onMounted(() => {
  fetchCardBalance()
  fetchHistory()
  
  if (userRole === 'STUDENT') {
    validateStudent()
    fetchStudentFees()
  }
  if (userRole === 'ADMIN') {
    fetchSchoolAccount()
  }
})
</script>

<style scoped>
.campus-payment {
  padding: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.history-section {
  margin-top: 24px;
}

.el-statistic {
  margin-bottom: 16px;
}
</style> 